﻿using ConfExpert.Forms.Base;

using DevTeamIT;
using System;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Entities
{
    public partial class ImageViewer : XPopupForm
    {
        BindingSource bs;
        string colName = string.Empty;

        public ImageViewer(Byte[] image)
        {
            Init();
            DataSet dsx = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Image", typeof(byte[])));
            DataRow dr = dt.NewRow();
            dr[0] = image;
            bs = new BindingSource(dsx, dt.TableName);
            colName = "Image";
        }

        private void Init()
        {
            this.WindowState = FormWindowState.Maximized;
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Sql">"Select VARBINARY from X" şeklinde Sql </param>
        public ImageViewer(string Sql)
        {
            Init();

            DataSet dsx = new DataSet();
            DataTable dt = Session.DataManager.ExecuteDataTableByQuery(Sql);
            dsx.Tables.Add(dt);
            bs = new BindingSource(dt.DataSet, dt.TableName);
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.DataType == typeof(Byte[]))
                {
                     colName = dc.ColumnName;
                    break;
                }
            }
        }

        private void DetailView_Load(object sender, EventArgs e)
        {
            this.MouseWheel += new MouseEventHandler(DetailView_MouseWheel);
            this.Resize += new EventHandler(DetailView_Resize);

            this.Text = "Detail x" + string.Format("{0:N1}", pictureEdit1.Bounds.Width / 385.0);

            pictureEdit1.DataBindings.Add("EditValue", bs, colName);
            pictureEdit1.BackgroundImage = null;
            
            System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
            aProp.SetValue(pictureEdit1, true, null);
        }

        void DetailView_Resize(object sender, EventArgs e)
        {
            this.Text = "DetailView x" + string.Format("{0:N2}", (pictureEdit1.Bounds.Width < pictureEdit1.Bounds.Height ? pictureEdit1.Bounds.Width : pictureEdit1.Bounds.Height) / 385.0);            
        }

        void DetailView_MouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta != 0 && (this.Height > 100 || e.Delta < 0))
            {
                this.SuspendLayout();
                this.Width -= e.Delta / 3;
                this.Height -= e.Delta / 3;
                this.ResumeLayout();
            }
        }
    }
}